﻿#include <QDebug>
#include <QDir>
#include <QFileInfo>
#include <private/qgeofiletilecache_p.h>

#include "QGeoTiledMappingManagerEngineCustom.h"
#include "MapEngine.h"
#include "UrlFactory.h"
#include "MapProvider.h"
#include "QGeoTileFetcherCustom.h"
//#include "QGeoFileTileCacheCustom.h"

QGeoTiledMappingManagerEngineCustom::QGeoTiledMappingManagerEngineCustom(const QVariantMap &parameters, QGeoServiceProvider::Error *error, QString *errorString)
    : QGeoTiledMappingManagerEngine()
{
    QGeoCameraCapabilities cameraCaps;
    cameraCaps.setMinimumZoomLevel(2.0);
    cameraCaps.setMaximumZoomLevel(MAX_MAP_ZOOM);
    cameraCaps.setSupportsBearing(true);
    //cameraCaps.setSupportsTilting(true);
    setCameraCapabilities(cameraCaps);

    setTileSize(QSize(256, 256));

#define MAP_TYPE(a, b, c, d, e, f)  QGeoMapType(a, b, c, d, e, f, QByteArray("CustomMap"), cameraCaps)

    /*
     * Google and Bing don't seem kosher at all. This was based on original code from OpenPilot and heavily modified to be used in QGC.
     */

    QList<QGeoMapType> mapList;
    QHashIterator<QString, MapProvider*> i(getMapEngine()->urlFactory()->getProviderTable());

    while(i.hasNext()){
        i.next();

        if(!i.value()->isElevationProvider()){
            mapList.append(MAP_TYPE(i.value()->getMapStyle(), i.key(), i.key(), false, false, getMapEngine()->urlFactory()->getIdFromType(i.key()) ));
        }
    }
    setSupportedMapTypes(mapList);

    //-- Users (QML code) can define a different user agent
    if (parameters.contains(QStringLiteral("useragent"))) {
        getMapEngine()->setUserAgent(parameters.value(QStringLiteral("useragent")).toString().toLatin1());
    }

    _setCache(parameters);

    // 从网络中加载瓦片
    setTileFetcher(new QGeoTileFetcherCustom(this));

#ifdef OnlyInMyCode
    //瓦片缓存-这部分参考QtLocation的esri部分源码
    //没有用QGeoFileTileCache，默认加载地缓存不会释放，还没找到原因，估计要分析它的源码
    QString cacheDirectory;
    if (parameters.contains("cachePath")) {
        qDebug() << "b: parameters.contains(\"cachePath\")";
        cacheDirectory = getMapEngine()->getCachePath();
    } else {
        qDebug() << "b: NOT parameters.contains(\"cachePath\")";
        cacheDirectory = QAbstractGeoTileCache::baseLocationCacheDirectory() + QString("TileCache");
    }

    qDebug() << "Tiles Cache Dir: " << cacheDirectory;
    // 设置地图缓冲,如果不需要缓存,可设置setMaxDiskUsage 大小,限制到小内存,,
    // setTileCache() 注释后会默认缓冲图片
    // 图片位置 C:\Users\Administrator\AppData\Local\cache\QtLocation\5.8\tiles\CustomMap
    auto tileCache = new QGeoFileTileCacheCustom(cacheDirectory, this);
    setTileCache(tileCache);
    if (tileCache) {
        // 这里是否和瓦片保存容量有关？
        tileCache->setMaxDiskUsage(1024 * 1024);  // 1 MB
        tileCache->setMaxMemoryUsage(1024 * 1024 * 100);  // 100 MB
    }
    //m_prefetchStyle = QGeoTiledMap::NoPrefetching;
#endif

    *error = QGeoServiceProvider::NoError;
    errorString->clear();
}

QGeoMap *QGeoTiledMappingManagerEngineCustom::createMap()
{
    //map->setPrefetchStyle(m_prefetchStyle);
    return new QGeoTiledMap(this, nullptr);
}

void QGeoTiledMappingManagerEngineCustom::_setCache(const QVariantMap &parameters)
{
    /*
    //瓦片缓存-这部分参考QtLocation的esri部分源码
    //没有用 QGeoFileTileCache ，默认加载地缓存不会释放，还没找到原因，估计要分析它的源码
    QString cacheDirectory;
    if (parameters.contains("cachePath")) {
        qDebug() << "b: parameters.contains(\"cachePath\")";
        cacheDirectory = getMapEngine()->getCachePath();
    } else {
        qDebug() << "b: NOT parameters.contains(\"cachePath\")";
        cacheDirectory = QAbstractGeoTileCache::baseLocationCacheDirectory() + QString("TileCache");
    }

    qDebug() << "Tiles Cache Dir: " << cacheDirectory;
    // 设置地图缓冲,如果不需要缓存,可设置setMaxDiskUsage 大小,限制到小内存,,
    // setTileCache() 注释后会默认缓冲图片
    // 图片位置 C:\Users\Administrator\AppData\Local\cache\QtLocation\5.8\tiles\CustomMap
    auto tileCache = new QGeoFileTileCacheCustom(cacheDirectory, this);
    setTileCache(tileCache);
    if (tileCache) {
        // 这里是否和瓦片保存容量有关？
        tileCache->setMaxDiskUsage(1024 * 1024);  // 1 MB
        tileCache->setMaxMemoryUsage(1024 * 1024 * 100);  // 100 MB
    }
    //m_prefetchStyle = QGeoTiledMap::NoPrefetching;
     */
    QString cacheDir;
    if (parameters.contains(QStringLiteral("mapping.cache.directory")))
        cacheDir = parameters.value(QStringLiteral("mapping.cache.directory")).toString();
    else {
        cacheDir = getMapEngine()->getCachePath();
        if(!QFileInfo::exists(cacheDir)) {
            if(!QDir::root().mkpath(cacheDir)) {
                qWarning() << "Could not create mapping disk cache directory: " << cacheDir;
                cacheDir = QDir::homePath() + QStringLiteral("/.mapscache/");
            }
        }
    }
    if(!QFileInfo::exists(cacheDir)) {
        if(!QDir::root().mkpath(cacheDir)) {
            qWarning() << "Could not create mapping disk cache directory: " << cacheDir;
            cacheDir.clear();
        }
    }
    qInfo() << "QGeoTiledMappingManagerEngineCustom::_setCache() cache directory:" << cacheDir;
    //-- Memory Cache
    uint32_t memLimit = 0;
    if (parameters.contains(QStringLiteral("mapping.cache.memory.size"))) {
        bool ok = false;
        memLimit = parameters.value(QStringLiteral("mapping.cache.memory.size")).toString().toUInt(&ok);
        if (!ok)
            memLimit = 0;
    }
    if(!memLimit)
    {
        //-- Value saved in MB
        memLimit = getMapEngine()->getMaxMemCache() * (1024 * 1024);
    }
    //-- It won't work with less than 1M of memory cache
    if(memLimit < 1024 * 1024)
        memLimit = 1024 * 1024;
    //-- On the other hand, Qt uses signed 32-bit integers. Limit to 1G to round it down (you don't need more than that).
    else if(memLimit > 1024 * 1024 * 1024)
        memLimit = 1024 * 1024 * 1024;

    qInfo() << "QGeoTiledMappingManagerEngineCustom::_setCache() memory size(Byte):" << memLimit;
    //-- Disable Qt's disk cache (sort of)
    QAbstractGeoTileCache *pTileCache = new QGeoFileTileCache(cacheDir);
    setTileCache(pTileCache);
    if(pTileCache)
    {
        //-- We're basically telling it to use 100k of disk for cache. It doesn't like
        //   values smaller than that and I could not find a way to make it NOT cache.
        //   We handle our own disk caching elsewhere.
        pTileCache->setMaxDiskUsage(1024 * 100);
        pTileCache->setMaxMemoryUsage(memLimit);
    }
}
